package cn.fch.gotrip.interceptor;

import cn.fch.gotrip.api.BeanResponse;
import cn.fch.gotrip.util.JwtUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @program: gotrip
 * @description:
 * @CreatedBy: fch
 * @create: 2023-01-14 23:19
 **/
public class AdminInterceptor implements HandlerInterceptor {
    @Autowired
    JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            response.setContentType("application/json;charset=utf-8");
            try (PrintWriter out = response.getWriter()) {
                out.write(JSONObject.toJSONString(BeanResponse.unauthorized("token不存在")));
                out.close();
                out.flush();
            }
            return false;
        }
        if (null == jwtUtil.getClaimsFromToken(token)) {
            response.setContentType("application/json;charset=utf-8");
            try (PrintWriter out = response.getWriter()) {
                out.write(JSONObject.toJSONString(BeanResponse.unauthorized("token过期")));
                out.close();
                out.flush();
            }
            return false;
        }
        return true;
    }
}
